#!/usr/bin/python
# wiki.py - Simple WSGI wikifier applicaton
#         - Runs as FastCGI or CGI script by default
#   
#   Copyright (c) Data Unity 2007
#
#   Redistribution and use in source and binary forms, with or without modification,
#   are permitted provided that the following conditions are met:
#   
#   Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#   
#   Redistributions in binary form must reproduce the above copyright notice, this
#   list of conditions and the following disclaimer in the documentation and/or other
#   materials provided with the distribution.
#   
#   Neither the name of the Data Unity nor the names of its contributors may be
#   used to endorse or promote products derived from this software without
#   specific prior written permission.
#  
#   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
#   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#   POSSIBILITY OF SUCH DAMAGE.


import urllib, time, re
import wikify

wikiList = None
def checkExists(wikifier, wikipage):
    global wikiList
    if wikiList is None:
        wikiList = urllib.urlopen(wikifier.srcdir).read()
    
    url = 'href="' + wikipage + ".wiki" + '"'
    if url in wikiList:
        return True
    return False
    
def loadWikified(environ, start_response):
    
    if 'PATH_INFO' in environ:
        parts = environ['PATH_INFO'].split("/")
    else:
        parts = ()
    
    if len(parts) < 2 or parts[-2] == "" or parts[-1] == "":
        import sys
        start_response("200 OK", [('Content-Type', 'text/plain')])
        return [file(sys.modules['__main__'].__file__).read()]
    
    source, page = parts[-2:]
    if page.endswith(".html") or page.endswith(".wiki"):
        page = page[:-5]
    
    srcdir = "http://%s.googlecode.com/svn/wiki/" % source
    url = "%s%s.wiki" % (srcdir, page)
    furl = urllib.urlopen(url)
    msgdict = furl.info().dict
    wikisource = furl.read()
    
    if "<title>404 Not Found</title>" in wikisource:
        start_response("404 Not Found", [('Content-Type', 'text/plain'),
                                         ('Date', msgdict['date'])])
        return ["Not Found"]

    start_response("200 OK", [('Content-Type', 'text/html'),
                              ('Date', msgdict['date'])])
    
    wikify.GoogleCode_Exists = checkExists
    w = wikify.Wikifier(wikify.GoogleCodeWikiFormat,
                        srcdir=srcdir,
                        suffix="")
    wikified = w.wikify(wikisource)
    return [wikified]

if __name__ == "__main__":
    try:
        from fcgi import WSGIServer
    except:
        try:
            from wsgi.cgigw import CGIGateway
        except:
            raise Exception("Cannot find web server interface.")
        else:
            CGIGateway()(loadWikified)
    else:
        WSGIServer(loadWikified).run()

